package com.example;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;

import java.util.Date;
import java.util.HashMap;

public class testGenerateJwt {
    @Test
    public void testGenerateJwt() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", 1);
        map.put("username", "admin");
        String jwt = Jwts.builder().signWith(SignatureAlgorithm.HS256, "itcast")
                .addClaims(map)
                .setExpiration(new Date(System.currentTimeMillis()+ 60*60*1000))
                .compact();
        System.out.println(jwt);
    }
    @Test
    public void testParseJwt() { // 解析JWT令牌
        //1.定义一个字符串，记录一个令牌
        String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImV4cCI6MTcyNTg1NzcwMH0.X3jR_c2uI6YRYnePD2va14jBD3azHIruF_nMpp7rLlI";
        //2.调用Jwts的静态方法解析，得到Claims对象
        Claims claims = Jwts.parser().setSigningKey("itcast") // 设置签名的秘钥
                .parseClaimsJws(jwt) //解析令牌
                .getBody(); // 得到Claims对象
        System.out.println(claims);
    }
}
